/**
 * @作者 faner
 * @创建时间 2020/12/31 10:44
 */
package com.faner.fast.word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class WordUtil {


    public static void export(Map<String, Object> params, HttpServletResponse response) {
        XWPFDocument doc;
        InputStream is = null;
        OutputStream os = null;
        XwpfTUtil xwpfTUtil = new XwpfTUtil();
        try {
            //word模版的名字
            String fileNameInResource = "a.docx";
            //会在跟路径下面查看temp.doc文件。(web项目中为classes文件下面)
            is = WordUtil.class.getClassLoader().getResourceAsStream(fileNameInResource);
            if (is != null) {
                doc = new XWPFDocument(is);
                xwpfTUtil.replaceInPara(doc, params);
                //替换表格里面的变量
                xwpfTUtil.replaceInTable(doc, params);
                os = response.getOutputStream();
                response.setContentType("application/vnd.ms-excel");
                //filename为导出的word的名字
                response.setHeader("Content-disposition", "attachment;filename=" + params.get("${title}") + ".docx");
                doc.write(os);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            xwpfTUtil.close(os);
            xwpfTUtil.close(is);
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
